package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 聊天室的服务端
 */
public class Server {
//    private PrintWriter[]allOut = {};
    private Collection<PrintWriter> allOut = new ArrayList<>();
    /**
     * java.net.ServerSocket
     * 运行在服务端上的，主要有两个职责:
     * 1.向系统申请服务端口，客户端就是通过该端口与服务端建立连接的
     * 2.监听该端口
     */
    private ServerSocket serverSocket;

    public Server() {
        try {
            System.out.println("正在启动服务端");
            this.serverSocket = new ServerSocket(8088);
            System.out.println("服务端启动完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start() throws IOException {
        while (true) {

            System.out.println("等待客户端连接");
            Socket  socket = serverSocket.accept();
            System.out.println("一个客户端连接了");
            Runnable runnable = new ClientHandler(socket);
            Thread thread = new Thread(runnable);
            thread.start();
        }
    }




    public static void main(String[] args) throws IOException {
        Server server = new Server();
        server.start();
    }

    private class ClientHandler implements Runnable{
        private Socket socket;
        private String host;
        public ClientHandler(Socket socket) {
            this.socket = socket;
            //通过socket获取远端计算机地址信息
            host = socket.getInetAddress().getHostAddress();
        }

        @Override
        public void run(){
            PrintWriter pw = null;
            {
                InputStream  inputStream = null;
                OutputStream outputStream = null;
                try {
                    inputStream = socket.getInputStream();
                    outputStream = socket.getOutputStream();


                    InputStreamReader isr = new InputStreamReader(
                            inputStream, StandardCharsets.UTF_8);
                    BufferedReader br = new BufferedReader(isr);
                    pw = new PrintWriter(
                            new BufferedWriter(
                                    new OutputStreamWriter(
                                            outputStream, StandardCharsets.UTF_8)), true);
                    /**
                     * 将对应该客户端的输出流存入allOut数组，
                     */
                    synchronized (Server.this) {
//                        allOut = Arrays.copyOf(allOut, allOut.length + 1);
//                        allOut[allOut.length - 1] = pw;
                        allOut.add(pw);
                    }
                    sendMessage(host + "上线了, 当前在线人数:"  + allOut.size());

                    String str;

                    while ((str = br.readLine()) != null) {
                        System.out.println(host + "说" + str);
                        sendMessage(host + "说：" + str);
                    }
                } catch (IOException e) {

                }finally {
                    //处理该客户端断开连接后的操作
                    try {
                        synchronized (Server.this) {
//                            for (int i = 0; i < allOut.si; i++) {
//                                if (pw == allOut[i]) {
//
//                                    allOut[i] = allOut[allOut.length - 1];
//                                    allOut = Arrays.copyOf(allOut, allOut.length - 1);
//                                    sendMessage(host + "下线了,当前在线人数:" + allOut.length);
//                                    break;
//                                }
//                            }
                            allOut.remove(pw);
                            sendMessage(host + "下线了,当前在线人数:" + allOut.size());

//                            while (it.hasNext()){
//                                PrintWriter p = (PrintWriter) it.next();
//                                if (pw == p){
//                                    it.remove();
//                                    sendMessage(host + "下线了,当前在线人数:" + allOut.size());
//                                    break;
//
//                                }
//                            }
                        }
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }
    /**
     * @author
     * @description //将消息给所有客户端
     * @date 2022/5/10 14:06
     * @param message
     */
    public void sendMessage(String message) {
        synchronized (Server.this) {
//            for (PrintWriter printWriter : allOut) {
//                printWriter.println(message);
//            }
            Iterator it = allOut.iterator();
            while (it.hasNext()){
                PrintWriter printWriter = (PrintWriter) it.next();
                printWriter.println(message);
            }
        }
    }
}



